package homework712;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//3：修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
//product为商品信息节点，discount表示是否折扣，如果是折扣商品，打七折；
//factoryaddr是工厂地址；
//itemno为商品编号，name为商品名称，price为商品单价，unit是计价单位，stockcount是库存量。
public class work3 {
	public static void main(String[] args) {
		SAXReader reader = new SAXReader();
		Document doc;
		Scanner in = new Scanner(System.in);
		System.out.println("输入商品编号");
		int b = in.nextInt();
		try {
			doc = reader.read(new File("src/homework712/products.xml"));
			Element root = doc.getRootElement();
			List<Element> list = root.selectNodes("product");

			for (int a = 0; a < list.size(); a++) {
				Element e = list.get(a);
				String itemno = e.selectSingleNode("itemno").getText();
				int i = Integer.parseInt(itemno);
				Element newProduct = root.addElement("product");
				while (i == b) {
					System.out.println("商品存在");
					System.out.println("输入商品数量");
					String c = in.next();

					String discount = e.attributeValue("discount");
					String factoryaddr = e.attributeValue("factoryaddr");
					if (factoryaddr != null) {
					} else {
						factoryaddr = "未知产地";
					}
					Element name = (Element) e.selectSingleNode("name");
					String n = name.getText();
					String price = e.selectSingleNode("price").getText();
					double p = Double.parseDouble(price);
					Element unit = (Element) e.selectSingleNode("unit");
					String u = unit.getText();
					Element d = (Element) e.selectSingleNode("stockcount");
					d.setText(c);
					String stockcount = e.selectSingleNode("stockcount").getText();
					int s = Integer.parseInt(stockcount);

					OutputFormat format = OutputFormat.createPrettyPrint();
					format.setEncoding("utf-8");
					XMLWriter xm = new XMLWriter(new FileWriter("src/homework712/products.xml"), format);
					xm.write(doc);
					xm.close();
					System.out.println("商品编号：" + i + " 名称：" + n + "产自" + factoryaddr + " 单价：" + p + " 现在还有" + s + u
							+ "目前打折状态：" + discount);

					return;

				}

			}
			System.out.println("该商品不存在！");

		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}

}
